package com.lancoo.ccas53.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.ccas53.entity.AssessmentMethod;
import com.lancoo.ccas53.entity.Course;
import com.lancoo.ccas53.entity.TeachingClass;
import com.lancoo.ccas53.exception.BizException;
import com.lancoo.ccas53.mapper.AssessmentMethodMapper;
import com.lancoo.ccas53.service.AssessmentMethodService;
import com.lancoo.ccas53.service.CourseService;
import com.lancoo.ccas53.service.TeachingClassService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service("assessmentMethodService")
public class AssessmentMethodServiceImpl extends ServiceImpl<AssessmentMethodMapper, AssessmentMethod> implements AssessmentMethodService {

    @Resource
    private TeachingClassService teachingClassService;
    @Resource
    private CourseService courseService;


    @Override
    public void addAssessmentMethod(AssessmentMethod assessmentMethod) {
        List<AssessmentMethod> list = this.lambdaQuery()
                .eq(AssessmentMethod::getTaskId, assessmentMethod.getTaskId())
                .eq(AssessmentMethod::getSchoolId, assessmentMethod.getSchoolId()).list();

        if (StringUtils.isBlank(assessmentMethod.getAssessmentName())) {
            throw new BizException("考核方式的名称不可以为空");
        }

        if (CollUtil.isNotEmpty(list)) {
            List<String> collect = list.stream().map(AssessmentMethod::getAssessmentName).collect(Collectors.toList());
            if (collect.contains(assessmentMethod.getAssessmentName())) {
                throw new BizException("该考核方式已经存在");
            }
        }

        this.save(assessmentMethod);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAssessmentMethod(Integer taskId, Long assessmentMethodId) {
        teachingClassService.lambdaUpdate()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getAssessmentId, assessmentMethodId)
                .set(TeachingClass::getAssessmentId, null)
                .set(TeachingClass::getAssessmentName, null)
                .update();

        courseService.lambdaUpdate()
                .eq(Course::getTaskId, taskId)
                .eq(Course::getAssessmentId, assessmentMethodId)
                .set(Course::getAssessmentId, null)
                .set(Course::getAssessmentName, null)
                .update();

        this.removeById(assessmentMethodId);

    }
}